package com.btb.adapter.schedule;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.btb.adapter.constant.Constants;
import com.btb.adapter.model.TaskConfig;
import com.btb.adapter.model.TransferRecord;
import com.btb.adapter.service.NotifyService;
import com.btb.adapter.service.TaskConfigService;
import com.btb.adapter.service.TransferRecordService;

import lombok.extern.slf4j.Slf4j;

/**
 * @author hqbzl
 *
 *         支付结果通知
 *
 *         上链结果通知远程
 */
@Slf4j
//@Component
@EnableScheduling
public class BuySuccessCallbackSchedule {

	@Autowired
	private TransferRecordService transferRecordService;
	@Autowired
	private NotifyService notifyService;
	@Autowired
	private TaskConfigService taskConfigService;

	@Scheduled(initialDelay = 100, fixedDelay = 1000 * 1)
	public void buySuccessCallbackSchedule() {
		log.error("buySuccessCallbackSchedule is start");
		final TaskConfig taskConfig = taskConfigService.findConfigByTaskNameCache(Constants.CONFIRM_PAY);
		if(Objects.isNull(taskConfig)) {
			log.error("buySuccessCallbackSchedule taskConfig is null");
			return;
		}
		Long status = Optional.ofNullable(taskConfig.getStatus()).orElse(1L);
		if(Objects.equals(1L, status)) {
			log.error("buySuccessCallbackSchedule taskConfig status is 1 stop");
			return;
		}
		final List<TransferRecord> query = transferRecordService.query(taskConfig);
		query.stream().filter(x -> x.isOk()).forEach(x -> {
			notifyService.pay(x, taskConfig);
		});
		log.error("buySuccessCallbackSchedule is end");
	}
}
